package com.chagee.store.operation.common.config;

import com.chagee.base.utils.HttpResponse;
import com.chagee.base.utils.HttpResponseUtil;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import java.net.BindException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 通用异常处理
 */
@Component
@ControllerAdvice
@Slf4j
public class ErrorHandler {

	private void errorLogger(Exception e) {
		log.error("request操作失败 ", e);
	}

	@ExceptionHandler(value = {Exception.class})
	public HttpResponse<?> exceptionHandler(Exception e) {
		errorLogger(e);
		return HttpResponseUtil.failure(BizErrorCode.FAIL);
	}

	@ExceptionHandler(value = {BizException.class})
	public HttpResponse<?> exceptionHandler(BizException e) {
		errorLogger(e);
		return HttpResponseUtil.build(null, e.getErrorCode(), e.getErrorMsg());
	}

	@ExceptionHandler(value = {BindException.class})
	public HttpResponse<?> bindExceptionHandler(BindException e) {
		errorLogger(e);
		return HttpResponseUtil.build(BizErrorCode.REQUEST_VALID_FAILED.getErrorCode(), e.getMessage(), null);
	}

	@ExceptionHandler(value = {MethodArgumentNotValidException.class})
	@ResponseBody
	public HttpResponse<?> argumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
		errorLogger(e);
		return HttpResponseUtil.build(BizErrorCode.REQUEST_VALID_FAILED.getErrorCode(), e.getMessage(), null);
	}

}
